/*
 * 绿电页面区域切换状态管理
 * 管理当前选中的区域和数据切换逻辑
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { GreenPowerApi } from '@/api/green-power'

export interface Region {
  id: string
  name: string
  code: string
  coordinates?: {
    longitude: number
    latitude: number
  }
  status?: string
}

export const useGreenPowerRegionStore = defineStore('greenPowerRegion', () => {
  // 状态
  const regions = ref<Region[]>([])
  const currentRegionId = ref<string>('')
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const currentRegion = computed(() => {
    return regions.value.find(region => region.id === currentRegionId.value)
  })

  const hasRegions = computed(() => {
    return regions.value.length > 0
  })

  // 方法
  const fetchRegions = async () => {
    try {
      loading.value = true
      error.value = null
      const response = await GreenPowerApi.getRegionList()
      regions.value = response.data.regions || []
      
      // 如果没有选中区域且有可用区域，选择第一个
      if (!currentRegionId.value && regions.value.length > 0) {
        currentRegionId.value = regions.value[0].id
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取区域列表失败'
      console.error('Failed to fetch regions:', err)
    } finally {
      loading.value = false
    }
  }

  const setCurrentRegion = (regionId: string) => {
    if (regions.value.some(region => region.id === regionId)) {
      currentRegionId.value = regionId
    } else {
      console.warn(`Region with id ${regionId} not found`)
    }
  }

  const switchToNextRegion = () => {
    if (regions.value.length === 0) return
    
    const currentIndex = regions.value.findIndex(region => region.id === currentRegionId.value)
    const nextIndex = (currentIndex + 1) % regions.value.length
    currentRegionId.value = regions.value[nextIndex].id
  }

  const switchToPrevRegion = () => {
    if (regions.value.length === 0) return
    
    const currentIndex = regions.value.findIndex(region => region.id === currentRegionId.value)
    const prevIndex = currentIndex === 0 ? regions.value.length - 1 : currentIndex - 1
    currentRegionId.value = regions.value[prevIndex].id
  }

  const reset = () => {
    regions.value = []
    currentRegionId.value = ''
    loading.value = false
    error.value = null
  }

  return {
    // 状态
    regions,
    currentRegionId,
    loading,
    error,
    
    // 计算属性
    currentRegion,
    hasRegions,
    
    // 方法
    fetchRegions,
    setCurrentRegion,
    switchToNextRegion,
    switchToPrevRegion,
    reset
  }
})